package com.yehui.algorithm.sword;

/**
 * 输入一个整数数组，判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。
 * 假设输入的数组的任意两个数字都互不相同。
 * Created by XuChunH on 2016/9/12.
 */
public class VerifySquenceOfBST {

    public boolean verifySquenceOfBST(int[] sequence) {
        if(sequence == null || sequence.length == 0) {
            return false;
        }
        return check(sequence, 0, sequence.length - 1);
    }

    private boolean check(int[] sequence, int start, int end){
        if(start >= end) {
            return true;
        }
        int i = start;
        while(i < end && sequence[i] < sequence[end]){
            i++;
        }
        for (int j = i; j < end; j++) {
            if(sequence[j] < sequence[end]){
                return false;
            }
        }
        return check(sequence, start, i - 1) && check(sequence, i, end - 1);
    }

}
